package com.guoguo.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.guoguo.base.StaticResource;
import com.guoguo.entity.MoneyFlow;
import com.guoguo.entity.Orders;
import com.guoguo.entity.PointFlow;
import com.guoguo.entity.UserExt;
import com.guoguo.entity.Users;
import com.guoguo.enums.PayEnum;
import com.guoguo.mapper.MoneyFlowMapper;
import com.guoguo.mapper.OrdersMapper;
import com.guoguo.mapper.PointFlowMapper;
import com.guoguo.mapper.UserExtMapper;
import com.guoguo.mapper.UsersMapper;
import com.guoguo.service.IPayService;
import com.guoguo.utils.RedisUtils;
import com.guoguo.utils.UUIDUtils;

/**
 * Created by Administrator on 2017/9/13 0013.
 */

     /*
                           _ooOoo_
                          o8888888o
                          88" . "88
                          (| -_- |)
                          O\  =  /O
                       ____/`---'\____
                     .'  \\|     |//  `.
                    /  \\|||  :  |||//  \
                   /  _||||| -:- |||||-  \
                   |   | \\\  -  /// |   |
                   | \_|  ''\---/''  |   |
                   \  .-\__  `-`  ___/-. /
                 ___`. .'  /--.--\  `. . __
              ."" '<  `.___\_<|>_/___.'  >'"".
             | | :  `- \`.;`\ _ /`;.`/ - ` : | |
             \  \ `-.   \_ __\ /__ _/   .-` /  /
        ======`-.____`-.___\_____/___.-`____.-'======
                           `=---='
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                 佛祖保佑       永无BUG
        */
@Service
public class PayServiceImpl implements IPayService {

    //UserExtr接口
    @Autowired
    private UserExtMapper userExtMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private MoneyFlowMapper moneyFlowMapper;

    @Autowired
    private PointFlowMapper pointFlowMapper;
    
    @Autowired
    private UsersMapper usersMapper;
    
    
    @Override
	public Orders createOrder(int payType, String userId) {
        //创建订单
        Orders orders = new Orders();
        orders.setOrderNo(UUIDUtils.getOrderNO());
        orders.setUserId(userId);
        orders.setCreateTime(new Date());
        orders.setUpdateTime(new Date());
        orders.setOrderType(payType);
        int num = ordersMapper.insert(orders);
        if (num > 0) {
            return orders;
        } else {
            return new Orders();
        }
    }

    /**
     * 订单明细
     *
     * @param payType
     * @param orderNo
     * @param albId
     * @param price
     * @return
     */
    @Override
    public int createPayJournal(int payType, String orderNo, String albId, String price) {
        int num = 0;
        if (payType == 1 || payType == 3) {
            PointFlow pointFlow = new PointFlow();
            pointFlow.setOrderNo(orderNo);
            pointFlow.setMoney(price);
            //1：充值；2：消费
            pointFlow.setPaymentType(payType == 1 ? 1 : 2);
            pointFlow.setAlbumId(albId);
            num = pointFlowMapper.insertSelective(pointFlow);
        }
        if (payType == 2 || payType == 4) {
            MoneyFlow moneyFlow = new MoneyFlow();
            moneyFlow.setOrderNo(orderNo);
            moneyFlow.setMoney(price);
            //1：充值；2：消费
            moneyFlow.setPaymentType(payType == 2 ? 1 : 2);
            moneyFlow.setAlbumId(albId);
            num = moneyFlowMapper.insertSelective(moneyFlow);
        }

        return num;
    }

    /**
     * 支付回调方法
     *
     * @param rechargeId
     * @param payType
     * @param userExt
     */
    @Override
	public void payCallBack(String rechargeId, int payType, UserExt userExt) {
        RedisUtils redisUtils = RedisUtils.getInstance();
        String payTypeMap = redisUtils.hget(StaticResource.SYS_INIT_RECHARGE_KEY, rechargeId);
        JSONObject rechargeJson = JSONObject.parseObject(payTypeMap);
        if (payType == PayEnum.PAY_TYPE_RECHARGE.getId()) {
            userExt.setPoint(userExt.getPoint() + rechargeJson.getIntValue("point"));
            //修改用户积分
            userExtMapper.insertUserExt(userExt);
            //订单类型
//            orders.setOrderType(0);
        }
        if (payType == PayEnum.PAY_TYPE_MEMBER.getId()) {
            userExt.setIsMember(true);

        }
    }

    @Override
    public List<Orders> getOrderList(String userId) {
        return ordersMapper.getOrderList(userId);
    }

	/**  
	 * @Description： 请求生成商户订单
	 * @author: WYZ 
	 * @throws Exception 
	 * @since: 2017年10月31日 下午7:44:37  
	 */
	@Override
	public Map<String, String> creatPayOrder(String mhtOrderType, String mhtOrderName, String mhtOrderAmt, String mhtOrderDetail, String mhtOrderTimeOut, String mhtOrderStartTime, String consumerId) throws Exception {
		Integer oderNum = null;
		Integer pointFlowNum = null;
		Map<String, String> resultData = new HashMap<String, String>();
        Orders orders = new Orders();
        PointFlow pointFlow = new PointFlow();
        Users user = new Users();
        String uuId = null;
        uuId = UUIDUtils.getOrderNO();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        orders.setOrderNo(uuId);
        orders.setUserId(consumerId);
        orders.setOrderType(1);
        orders.setCreateTime(sdf.parse(mhtOrderStartTime));
        orders.setOrderTimeOut(mhtOrderTimeOut);
        orders.setStatus(3);
        
        pointFlow.setOrderNo(uuId);
        pointFlow.setPaymentType(1);
        pointFlow.setMoney(mhtOrderAmt);
        pointFlow.setAlbumName(mhtOrderName);
        pointFlow.setOrderDetail(mhtOrderDetail);
        
        user = usersMapper.selectByPrimaryKey(consumerId);
        if(user != null && StringUtils.isNotEmpty(user.getNickname())){
        	resultData.put("consumerName", user.getNickname());//消费者名称
        	oderNum = ordersMapper.insert(orders);
        }
        pointFlowNum = pointFlowMapper.insertSelective(pointFlow);
        if (oderNum > 0 && pointFlowNum > 0) {
        	resultData.put("mhtOrderNo", uuId);//商户订单号
        }else{
        	return null;
        }
		return resultData;
        
    }
	
	/**  
	 * @Description： 商户通知结果
	 * @author: WYZ 
	 * @throws ParseException 
	 * @since: 2017年11月2日 下午12:19:58  
	 */
	@Override
	public boolean creatPayMessageNoti(String mhtOrderNo, String tradeStatus, String payTime,String nowPayOrderNo,String channelOrderNo) throws ParseException {
		boolean isSuccess = false;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		isSuccess = ordersMapper.updateOrderStatus(mhtOrderNo,"0",sdf.parse(payTime),nowPayOrderNo,channelOrderNo);
		return isSuccess;
	}
	

	/**  
	 * @Description： 商户支付结果
	 * @author: WYZ 
	 * @throws ParseException 
	 * @since: 2017年11月2日 下午12:19:58  
	 */
	@Override
	public boolean creatPayMessage(String mhtOrderNo, String tradeStatus, String payTime,String nowPayOrderNo,String channelOrderNo,String mhtOrderAmt) throws ParseException {
		boolean isSuccess = false;
		Integer updateCount = null;
		Integer oderNum = null;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		isSuccess = ordersMapper.updateOrderStatus(mhtOrderNo,"1",sdf.parse(payTime),nowPayOrderNo,channelOrderNo);
		if(isSuccess){
			updateCount = pointFlowMapper.updateDeductMoney(mhtOrderNo,mhtOrderAmt);
			if(updateCount > 0){
				Orders orders = new Orders();
				Orders ordersC = new Orders();
				orders.setOrderNo(UUIDUtils.getOrderNO());
		        orders.setOrderType(3);
		        orders.setCreateTime(new Date());
		        orders.setStatus(1);
		        ordersC = ordersMapper.selectByPrimaryKey(mhtOrderNo);
		        if(ordersC != null && StringUtils.isNotBlank(ordersC.getUserId())){
		        	orders.setUserId(ordersC.getUserId());
		        }
		        oderNum = ordersMapper.insert(orders);
		        if(oderNum > 0){
		        	isSuccess = true;
		        }else{
		        	isSuccess = false;
		        }
			}else{
				isSuccess = false;
			}
		}
		return isSuccess;
	}

	/**  
	 * @Description： 更新支付报文数据
	 * @author: WYZ 
	 * @since: 2017年11月2日 下午3:25:24  
	 */
	@Override
	public Integer updateNeedcheckmsg(String mhtOrderNo,String needcheckmsg) {
		Integer needcheckmsgAccount = null;
		Date updateTime = new Date();
		needcheckmsgAccount = ordersMapper.updateNeedcheckmsg(mhtOrderNo,needcheckmsg,updateTime);
		return needcheckmsgAccount;
	}
    
	/**  
	 * @Description： 查询订单表的数据签名
	 * @author: WYZ 
	 * @since: 2017年11月2日 下午3:25:24  
	 */
	@Override
	public String selectSignature(String mhtOrderNo) {
		String signature = null;
		Orders orders = new Orders();
		orders = ordersMapper.selectByPrimaryKeyNew(mhtOrderNo);
		if(orders != null && StringUtils.isNotEmpty(orders.getNeedcheckmsg())){
			signature = orders.getNeedcheckmsg();
		}
		return signature;
	}


}
